import 'dart:async';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:x3_base_core/x3_base_core.dart';
import 'package:x3_component_core/x3_component_core.dart';
import 'package:x3_form_core/provider/base_request_form_provider.dart';
import 'package:x3_form_core/business_components/base_request_form_container.dart';

class BaseRequestFormImage extends StatefulWidget {
  BaseRequestFormImage({Key key, @required this.request, this.requestSaveData}) : super(key: key);

  final BaseHttpRequestModel request;

  final RequestSaveData requestSaveData;

  @override
  _BaseRequestFormImageState createState() => _BaseRequestFormImageState();
}

class _BaseRequestFormImageState extends State<BaseRequestFormImage> {
  final List<String> _bottomSheetItems = ['拍照', '从相册中选择', '取消'];
  BaseRequestFormProvider _baseRequestFormProvider;
  String get _imageUrl => _baseRequestFormProvider.getDataSource(widget.request) ?? '';
  StreamController _streamController = StreamController<String>();

  @override
  void dispose() {
    _streamController.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    _baseRequestFormProvider = BaseRequestFormProvider.of(context);

    return BaseRequestFormContainer(
      request: widget.request,
      suffixIcon: _buildIcon(),
      showSuffixIcon: !_baseRequestFormProvider.isReadonly(widget.request),
      onPress: () => _onUploadImage(),
      child: StreamBuilder<String>(
        initialData: _imageUrl,
        stream: _streamController.stream,
        builder: (context, snapshot) {
          String img = snapshot.data;
          return BaseImageComponent(imageUrl: img, width: 32, height: 32, circular: 32, size: BaseImageSizeEnum.original);
        },
      ),
    );
  }

  _buildIcon() {
    return Container(child: Icon(BaseIconData.x3Camera, color: BaseBodyTheme.iconColor, size: 16));
  }

  void _onUploadImage() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext bottomContext) {
        return Container(
          height: 170.0,
          child: ListView.separated(
            itemBuilder: (BuildContext itemContext, int index) => _buildBottomSheetItem(context, bottomContext, index),
            itemCount: _bottomSheetItems.length,
            separatorBuilder: (BuildContext context, int index) => BaseComponentUtils.buildHorizontalDivider(),
          ),
        );
      },
    );
  }

  Widget _buildBottomSheetItem(BuildContext context, BuildContext bottomContext, int index) {
    return InkWell(
      onTap: () {
        Navigator.pop(bottomContext);
        this._onBottomSheetItemPress(index);
      },
      child: Container(
        alignment: Alignment.center,
        height: 50.0,
        child: Text(_bottomSheetItems[index], style: TextStyle(fontSize: 14.0, color: Theme.of(context).textTheme.bodyText2.color)),
      ),
    );
  }

  _onBottomSheetItemPress(int index) {
    if (index == 0) _getImageForCamera(context);

    if (index == 1) _getImageForGallery(context);
  }

  _getImageForCamera(BuildContext context) async {
    PickedFile file = await ImagePicker().getImage(source: ImageSource.camera);
    this._upLoadImage(context, file);
  }

  _getImageForGallery(BuildContext context) async {
    PickedFile file = await ImagePicker().getImage(source: ImageSource.gallery);
    this._upLoadImage(context, file);
  }

  /// 保存照片
  _upLoadImage(BuildContext context, PickedFile pickedFile) async {
    if (pickedFile == null) return;
    BaseComponentUtils.showLoadingDialog(context, hint: '正在上传图片');
    BaseHttpResultModel result = await dioUtil.fetchUploadFile(pickedFile.path);
    BaseComponentUtils.hideLoadingDialog(context);
    if (result.success == true) {
      String imageUrl = '${result.data['fileSource']}${result.data['fileRealPath']}';
      _baseRequestFormProvider.setDataSource(widget.request, imageUrl);
      _streamController.sink.add(imageUrl);
      if (widget.requestSaveData != null) {
        widget.requestSaveData(widget.request, _baseRequestFormProvider.getMapDataSource(widget.request));
      }
    }
  }
}
